package datasource

import (
	"database/sql"
	"fmt"
	"gitee.com/kristas/booting-go/framework"
	"gitee.com/kristas/booting-go/framework/core/statement/types"
	_ "github.com/go-sql-driver/mysql"
	"time"
)

func init() {
	framework.Component(new(MySqlDriver))
}

type MySqlDriver struct {
	types.DataSourceDriver `name:"datasource_driver:mysql" type:"database/sql" driver:"github.com/go-sql-driver/mysql"`
}

func (d *MySqlDriver) Open(properties *DataSourceProperties) (DB, error) {
	dsn := fmt.Sprintf("%s:%s@%s", properties.Username, properties.Password, properties.Url)
	conn, err := sql.Open("mysql", dsn)
	if err != nil {
		return nil, err
	}
	d.initConn(conn, properties)
	return conn, nil
}

func (d *MySqlDriver) initConn(conn *sql.DB, properties *DataSourceProperties) {
	if properties.ConnMaxLifeTime != 0 {
		conn.SetConnMaxLifetime(time.Second * time.Duration(properties.ConnMaxLifeTime))
	}
	if properties.ConnMaxIdleTime != 0 {
		conn.SetConnMaxIdleTime(time.Second * time.Duration(properties.ConnMaxIdleTime))
	}
	if properties.MaxIdleConns != 0 {
		conn.SetMaxIdleConns(properties.MaxIdleConns)
	}
	if properties.MaxOpenConns != 0 {
		conn.SetMaxOpenConns(properties.MaxOpenConns)
	}
}
